<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">


                <el-button type="primary" @click="()=>this.editVisible=true" v-if="hasPermission('role:add')">添加角色</el-button>
            </div>
            <el-table
                    :data="roleList.filter(role=>role.role.isDeleted===0)"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    v-if="hasPermission('role:select')"

            >
                <el-table-column label="ID" width="55" align="center">
                    <template slot-scope="scope">
                        {{scope.row.role.roleId}}
                    </template>
                </el-table-column>
                <el-table-column label="角色代码">
                    <template slot-scope="scope">
                        {{scope.row.role.roleName}}
                    </template>
                </el-table-column>
                <el-table-column label="角色名">
                    <template slot-scope="scope">
                        {{scope.row.role.description}}
                    </template>
                </el-table-column>


                <el-table-column label="菜单&权限">
                    <template slot-scope="scope">
                        <el-row v-for="menu in scope.row.menuVO">
                            <span style="margin-right: 4px">{{menu.menuName}}</span>
                            <el-tag v-for="permission in menu.permissionList"
                                    style="margin-right: 7px;margin-bottom: 7px">
                                {{permission.description}}
                            </el-tag>
                        </el-row>
                    </template>

                </el-table-column>

                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.row.role.roleId)"
                                v-if="hasPermission('role:update')"
                        >编辑
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                v-if="hasPermission('role:delete')"
                                @click="handleDelete(scope.row.role.roleId)"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>


            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="pageNum"
                        :page-size="4"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <el-dialog title="编辑角色" :visible.sync="editVisible1" width="45%" label-position="left" label-width="150px"
                   size="medium">
            <el-form ref="form1" :model="form1" label-width="70px" :rules="rules2">
                <el-form-item label="角色码" prop="roleName">
                    <el-input placeholder="角色代码" v-model="form1.roleName" style="width: 70%;"
                              :value="form1.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色名" prop="description">
                    <el-input placeholder="角色名" v-model="form1.description" :value="form1.description"></el-input>
                </el-form-item>
                <el-form-item label="权限">
                    <el-checkbox-group v-model="form1.permissionList" v-for="menuVO in permissionList">
                        <el-tag type="success" style="margin-right: 10px" effect="dark">
                            {{menuVO.menuName}}
                        </el-tag>

                        <el-checkbox v-for="permission in menuVO.permissionList"
                                     :label="permission.description"></el-checkbox>
                        <br>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="updateRole">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="添加角色" :visible.sync="editVisible" width="45%" label-position="left" label-width="150px"
                   size="medium">
            <el-form ref="form" :model="form" label-width="70px" :rules="rules">
                <el-form-item label="角色码" prop="roleName">
                    <el-input placeholder="角色代码" v-model="form.roleName" style="width: 70%;"></el-input>
                </el-form-item>

                <el-form-item label="角色名" prop="description">
                    <el-input placeholder="角色名" v-model="form.description"></el-input>
                </el-form-item>

                <el-form-item label="权限" prop="permissionList">
                    <el-checkbox-group v-model="form.permissionList" v-for="(menuVO,index) in permissionList">
                        <el-button style="margin-right: 10px" @click="savePermission(menuVO.permissionList,index)"
                                   :type="selectArr[index]">
                            {{menuVO.menuName}}
                        </el-button>
                        <el-checkbox v-for="permission in menuVO.permissionList"
                                     :label="permission.description"></el-checkbox>
                        <br>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import { fetchData } from '../../api/index';
    import { getAllRoles, addRole, deleteRole, getRole, updateRole } from '../../api/role';
    import { getAllPermission } from '../../api/permission';
    import { hasMenu, hasPermission, permissionListContain,getPermission } from '../../utils/authority';

    export default {
        name: 'role',
        data() {
            return {
                permissionList: [],
                permissionList1: [],
                roleList: [],
                editVisible1: false,
                pageNum: 1,
                query: {
                    address: '',
                    name: '',
                    pageIndex: 1,
                    pageSize: 10
                },
                tableData: [],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                pageTotal: 0,
                selectArr: [],
                selectArr1: [],
                roleVO: {},
                form1: {
                    roleName: '',
                    permissionList: [],
                    description: ''
                },
                form: {
                    roleName: '',
                    permissionList: [],
                    description: ''
                },
                idx: -1,
                id: -1,
                rules2: {
                    description: [
                        { required: true, message: '角色名不能为空', trigger: 'change' }
                    ],
                    roleName: [
                        { required: true, message: '角色码不能为空', trigger: 'change' }
                    ]
                },
                rules: {
                    permissionList: [
                        { required: true, message: '权限不能为空', trigger: 'change' }
                    ],
                    description: [
                        { required: true, message: '角色名不能为空', trigger: 'change' }
                    ],
                    roleName: [
                        { required: true, message: '角色码不能为空', trigger: 'change' }
                    ]

                }
            };
        },
        created() {
            this.getData();

        },
        methods: {
            permissionContain(permissionList) {
                return permissionListContain(permissionList);
            },
            hasPermission(permission) {
                return hasPermission(permission);
            },
            hasMenu(menuCode) {
                return hasMenu(menuCode);
            },
            savePermission(permissionList, index) {
                if (this.selectArr[index] === 'default') {
                    this.selectArr[index] = 'success';
                    permissionList.map(item => item.description).forEach(item => this.form.permissionList.push(item));
                } else {
                    this.selectArr[index] = 'default';
                    this.form.permissionList = this.form.permissionList.filter(item => permissionList.map(item => item.description).indexOf(item) === -1);

                }

            },
            // 获取 easy-mock 的模拟数据
            getData() {


                getAllRoles({
                    pageNum: 1
                }).then(res => {
                    this.roleList = res.data.data.list;
                    this.pageNum = res.data.data.pageNum;
                    this.pageTotal = res.data.data.total;
                    console.log(this.pageTotal);
                });

                getAllPermission().then(res => {
                    this.permissionList = res.data.data;
                    let len = this.permissionList.length;
                    this.selectArr = [];
                    for (let i = 0; i < len; i++) {
                        this.selectArr.push('default');
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(roleId) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        deleteRole({
                            roleId: roleId
                        }).then(res => {
                            if (res.data.resultCode === 204) {
                                this.$message.success('删除成功');
                                this.getData();
                            } else {
                                this.$message.error('删除失败');
                            }
                        });

                    })
                    .catch(() => {
                    });
            },
            // 编辑操作
            handleEdit(roleId) {
                this.editVisible1 = true;
                getRole({
                    roleId: roleId
                }).then(res => {
                    this.roleVO = res.data.data;
                    this.form1.roleName = this.roleVO.role.roleName;
                    this.form1.description = this.roleVO.role.description;
                    this.form1.permissionList = this.roleVO.menuVO;
                    this.permissionList1 = this.roleVO.menuVO;
                    let tempArr = [];
                    for (let i = 0; i < this.permissionList1.length; i++) {
                        let temp = this.permissionList1[i].permissionList;
                        for (let j = 0; j < temp.length; j++) {
                            tempArr.push(temp[j].description);
                        }
                    }
                    this.form1.permissionList = tempArr;
                });
            },


            updateRole() {

                console.log('updateRole');
                this.$refs.form1.validate(valid => {
                    if (valid) {
                        let descriptionList = this.form1.permissionList;
                        delete this.form1['permissionList'];
                        this.form1['descriptions'] = descriptionList;
                        updateRole(JSON.stringify(this.form1)).then(res => {
                            if (res.data.resultCode === 201) {
                                this.$message.success('修改成功');
                                this.form1 = {
                                    roleName: '',
                                    permissionList: [],
                                    description: ''
                                };
                                this.editVisible1 = false;
                                this.getData();
                            } else {
                                this.$message.error('修改失败');
                                console.log('error submit!!');


                                return false;
                            }
                        });

                    }
                });
            },
            // 保存编辑
            saveEdit() {

                this.$refs.form.validate(valid => {
                    if (valid) {
                        let descriptionList = this.form.permissionList;
                        delete this.form['permissionList'];
                        this.form['descriptions'] = descriptionList;
                        addRole(JSON.stringify(this.form)).then(res => {
                            if (res.data.resultCode === 201) {
                                this.$message.success('添加成功');
                                this.form = {
                                    roleName: '',
                                    permissionList: [],
                                    description: ''
                                };
                                this.editVisible = false;
                                this.getData();

                            } else {
                                this.$message.error('添加失败');
                                console.log('error submit!!');

                                return false;
                            }
                        });

                    }
                });


            },
            // 分页导航
            handlePageChange(val) {
                getAllRoles({
                    pageNum: val
                }).then(res => {
                    this.roleList = res.data.data.list;
                    this.pageNum = res.data.data.pageNum;
                });
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>
